<?php

/* This routine sets 
   $IS_LOGGED_ON
 * $USER_ID
 * $SESSION_ID
 * 
 * on the basis of the POST variables SessionID/UserID, Username/Password combos
*/


$GLOBALS['IS_LOGGED_ON'] = 0;
$GLOBALS['USER_ID'] = -1;
$GLOBALS['SESSION_ID'] = -1;

// Check POST variables 
// If SessionID is set - check that it is valid for the given UserID

// echo "Authenication<br>\n";
if(isset($_POST['SessionID'])&&(isset($_POST['UserID'])))
{
	$database=$DATABASE->Recopy();
	$timeNow = new DateTime("now");
	$sql = "SELECT SessionID, UserID, Expires FROM Sessions WHERE SessionID = '".$_POST['SessionID']."' AND UserID = '".$_POST['UserID']."' AND Expires > '".$timeNow->format("Y-m-d H:i")."'";
//	echo $sql."<br>\n";
	$database->executeSQL($sql);
	if($row=$database->getRow()) 
	{
		$GLOBALS['IS_LOGGED_ON'] = 1;
		$GLOBALS['USER_ID'] = $_POST['UserID'];
		$GLOBALS['SESSION_ID'] = $_POST['SessionID'];
	}
}

elseif(isset($_POST['UserName'])&&(isset($_POST['Password'])))
{
	$database=$DATABASE->Recopy();
	$sql = "SELECT * FROM SnapUsers WHERE LongName = '".$_POST['UserName']."' AND Password = '".$_POST['Password']."'";
//	echo $sql."<br>\n";
	$database->executeSQL($sql);
	if($row=$database->getRow())
	{
		$database1=$database->Recopy();
		$GLOBALS['USER_ID'] = $row['SnapUserID'];
		$Expires = strftime("%Y-%m-%d %H:%M:%S",time() + 86400); //86400 -> 24 hours
		$sql1="INSERT INTO Sessions (Expires, Username, UserID) Values('".$Expires."','".$row['LongName']."','".$row['SnapUserID']."')";
//		echo $sql1."<br>\n";
		$database1->executeSQL($sql1);
		$SessionID = mysql_insert_id();
		if($SessionID==0)$SessionID=-1;
//		echo $SessionID."<br>\n";
		$GLOBALS['SESSION_ID'] = $SessionID;
		if($GLOBALS['SESSION_ID'] != -1)$GLOBALS['IS_LOGGED_ON'] = 1;
		
	}
	
}



/*
echo "IS_LOGGED_ON = ".$GLOBALS['IS_LOGGED_ON']."<br>\n";
echo "USER_ID = ".$GLOBALS['USER_ID']."<br>\n";
echo "SESSION_ID = ".$GLOBALS['SESSION_ID']."<br>\n";
*/

